package com.huifaapp.mall.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.huifaapp.mall.R;
import com.huifaapp.mall.adapter.AllOrderAdapter;

import com.huifaapp.mall.dialogs.LoadingDialog;
import com.huifaapp.mall.fragment.AllOrdersFragment;
import com.huifaapp.mall.fragment.GoodsReceivedFramgnet;
import com.huifaapp.mall.fragment.PendingCommFragment;
import com.huifaapp.mall.fragment.PendingDeliveryFragment;
import com.huifaapp.mall.fragment.PendingPayFragment;
import com.huifaapp.mall.view.LoadingDialogd;
import com.kepler.jd.Listener.LoginListener;
import com.kepler.jd.Listener.OpenAppAction;
import com.kepler.jd.login.KeplerApiManager;
import com.kepler.jd.sdk.bean.KelperTask;
import com.kepler.jd.sdk.bean.KeplerAttachParameter;
import com.kepler.jd.sdk.exception.KeplerBufferOverflowException;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;



public class AllOrderActivity extends AppCompatActivity {

    private TabLayout tab_layout;
    private ViewPager viewpager;
    private List<Fragment> fragments = new ArrayList<>();
    private List<String> list=new ArrayList<>();
    private int roomid;
    private LinearLayout LinearTop;
    private ImageView Imback;
    private Button bt_chakandingdan;
    Handler mHandler;
    KeplerAttachParameter mKeplerAttachParameter = new KeplerAttachParameter();//这个是即时性参数  可以设置
    KelperTask mKelperTask;
    private AllOrderAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_order);
        Intent intent = getIntent();

        initView();
        list.add("全部");
        list.add("待付款");
        list.add("待发货");
        list.add("待收货");
        list.add("待评论");
        roomid = intent.getIntExtra("roomid",0);
        adapter = new AllOrderAdapter(getSupportFragmentManager(),fragments,list);
        viewpager.setAdapter(adapter);
        tab_layout.setupWithViewPager(viewpager);
        tab_layout.setTabsFromPagerAdapter(adapter);
        viewpager.setCurrentItem(roomid);
        viewpager.setOffscreenPageLimit(5);

//        if (roomid!=0)
//        {
//            LinearTop.setVisibility(View.GONE);
//        }
//        else {
//            LinearTop.setVisibility(View.VISIBLE);
//        }

        tab_layout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
//
//                if (position!=0){
//                    LinearTop.setVisibility(View.GONE);
//                }else {
//                    LinearTop.setVisibility(View.VISIBLE);
//                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


        bt_chakandingdan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            if(KeplerApiManager.getWebViewService().isKeplerLogined()){
                try {
                    mKelperTask= KeplerApiManager.getWebViewService().openOrderListPage(
                            mKeplerAttachParameter,AllOrderActivity.this,mOpenAppAction,15);
                } catch (KeplerBufferOverflowException e) {

                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                }else{
                final LoginListener mLoginListener = new LoginListener() {
                    @Override public void authSuccess(Object token) {
                        // TODO Auto-generated method stub
                        Toast.makeText(AllOrderActivity.this, token + "", Toast.LENGTH_SHORT).show();
//                showToken();
                        if(KeplerApiManager.getWebViewService().isKeplerLogined()){
                            try {
                                mKelperTask= KeplerApiManager.getWebViewService().openOrderListPage(
                                        mKeplerAttachParameter,AllOrderActivity.this,mOpenAppAction,15);
                            } catch (KeplerBufferOverflowException e) {

                                e.printStackTrace();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    @Override public void authFailed(int errorCode) {
                        // TODO Auto-generated method stub
                        switch (errorCode)
                        { case KeplerApiManager.KeplerApiManagerLoginErr_Init:// 初始化失败 break;
                            case KeplerApiManager.KeplerApiManagerLoginErr_InitIng:// 初始化没有完成 break;
                            case KeplerApiManager.KeplerApiManagerLoginErr_openH5authPageURLSettingNull://跳转url // 为null break;
                            case KeplerApiManager.KeplerApiManagerLoginErr_getTokenErr:// 获取失败(OAuth授权之后，获取cookie过程出错) break;
                            case KeplerApiManager.KeplerApiManagerLoginErr_User_Cancel:// 用户取消 break;
                            case KeplerApiManager.KeplerApiManagerLoginErr_AuthErr_ActivityOpen://打开授权页面失败 break;
                            default: break;
                        }
//                Toast.makeText(AllOrderActivity.this, errorCode + ":authFailed", Toast.LENGTH_SHORT).show();
                        Log.e("jdSHOUQUAN",errorCode+":authFailed");
                    } };
                KeplerApiManager.getWebViewService().login(AllOrderActivity.this, mLoginListener);

            }
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();




        viewpager.setCurrentItem(roomid);
        adapter.notifyDataSetChanged();

    }

    private void initView() {
        mHandler = new Handler();
        tab_layout = (TabLayout) findViewById(R.id.tab_layout);
        viewpager = (ViewPager) findViewById(R.id.viewpager);
        Imback = (ImageView) findViewById(R.id.iv_allorder_back);
        bt_chakandingdan= (Button) findViewById(R.id.bt_chakandingdan);
        Imback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        fragments.add(new AllOrdersFragment());
        fragments.add(new PendingPayFragment());
        fragments.add(new PendingDeliveryFragment());
        fragments.add(new GoodsReceivedFramgnet());
        fragments.add(new PendingCommFragment());
        LinearTop = (LinearLayout) findViewById(R.id.lineartop);


    }


    OpenAppAction mOpenAppAction = new OpenAppAction() {
        @Override
        public void onStatus(final int status) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (status == OpenAppAction.OpenAppAction_start) {//开始状态未必一定执行，
                        dialogShow();
                    } else {
                        mKelperTask=null;
                        dialogDiss();
                    }
                }
            });
        }
    };
    LoadingDialogd dialog;

    private void dialogShow() {
        if (dialog == null) {
            dialog = new LoadingDialogd(this);
//            dialog.setCanceledOnTouchOutside(false);
            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (mKelperTask != null) {//取消
                        mKelperTask.setCancel(true);
                    }
                }
            });
        }
        dialog.show();
    }

    private void dialogDiss() {
        if(dialog!=null)
            dialog.dismiss();
    }
    private void showUserStatus() {


//        // 并不保证是登录状态
//        if (KeplerApiManager.getWebViewService().isKeplerLogined()) {
//            login_lin.setVisibility(View.VISIBLE);
//            login.setVisibility(View.INVISIBLE);
//        } else {
//            login_lin.setVisibility(View.INVISIBLE);
//            login.setVisibility(View.VISIBLE);
//        }

    }
}
